#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Ka3u6y6a'

import os
import ConfigParser

settpath = os.getcwd()+ '\\engine\\cbviewer.cfg'
print settpath

def settingsTest():
    """
    Try to open cbviewer.cfg
    """
    if not os.path.exists(settpath):
        print 'cbviewer.cfg not found'
        #Renew config file
        settingsDefaultCreate()

        #Create Projects dir
        projpath = os.path.join(os.path.expanduser("~"), "Documents\\CBviewer")
        if not os.path.exists(projpath):
            print 'Create new dir CBviewer'
            os.makedirs(projpath)
        return False

    else: return True

def settingsDefaultCreate():
    """
    Create cbviewer.cfg file. If cbviewer.cfg exist, override him.
    """
    config = ConfigParser.RawConfigParser()

    print 'Create new cbviewer.cfg'
    path = os.path.join(os.path.expanduser("~"), "Documents\\CBviewer") #Get default path to My Docs
    print path

    #Fill config file
    try:
        config.add_section('Main')
        with open(settpath, 'wb') as configfile:
            config.write(configfile)
    except: print 'Main section exist'

    config.set('Main', 'ProjectsPath', path)
    config.set('Main', 'CBVtheme', 'Plastique')
    config.set('Main', 'diffColor', '100.31.31.200')
    config.set('Main', 'diffSens', 1)
    config.set('Main', 'browserWinWidth', 1100)
    config.set('Main', 'browserWinHight', 800)

    with open(settpath, 'wb') as configfile:
        config.write(configfile)

def saveProjectInfo(path, url, ie, ff, ch):
    """
    Saving information about project to Test-Case folder
    """
    config = ConfigParser.RawConfigParser()

    infopath = os.path.join(path, 'info.cfg')
    print infopath
    try:
        config.add_section('Info')
        with open(infopath, 'wb') as configfile:
            config.write(configfile)
    except: print 'Info section exist'

    config.set('Info', 'url', url.encode('utf-8'))
    config.set('Info', 'ie', ie)
    config.set('Info', 'ff', ff)
    config.set('Info', 'ch', ch)

    with open(infopath, 'wb') as configfile:
        config.write(configfile)

def getSett(name, section = 'Main'):
    """
    Try to read <Section><NAME> parameter from config file. If exception - renew config file.
    -- Section, Name
    """
    config = ConfigParser.RawConfigParser()
    try:
        config.read(settpath)
        parameter = config.get(section, name)
        print 'Config file reading successful'
    except:
        print 'Error reading config file. Config renewed'
        settingsDefaultCreate()
        config.read(settpath)
        parameter = config.get(section, name)

    return parameter

def getProjectList():
    """
    Returns project list from project folder
    """
    config = ConfigParser.RawConfigParser()
    pass


